05. Construct Desired URL from User Preferences

Construct Desired URL from User Preferences

So far we've been requesting earthquakes using a hardcoded, fixed URL. However, now we need to insert our preference for minimum earthquake magnitude into the URL as a query parameter. We could do this with some tricky string concatenation, but there's a better way using the Uri.Builder class.

Wait, what's a URI again? A URI, or uniform resource identifier, is a more general URL. While a URL always points to a resource that's available on a computer network somewhere, a URI can identify a much broader range of things, from files and email mailboxes, to physical objects like books.

Since URLs are a subset of URIs, it made more sense for Android to just provide ways to manipulate URIs, since those will work for URLs as well

First, let's modify the value of the USGS_REQUEST_URL constant in the EarthquakeActivity class to the base URI. Later we’ll use UriBuilder.appendQueryParameter() methods to add additional parameters to the URI (such as JSON response format, 10 earthquakes requested, minimum magnitude value, and sort order).

In EarthquakeActivity.java:

 private static final String USGS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query";

Then we can replace the body of onCreateLoader() method to read the user’s latest preferences for the minimum magnitude, construct a proper URI with their preference, and then create a new Loader for that URI.

In EarthquakeActivity.java:

 @Override
 public Loader<List<Earthquake>> onCreateLoader(int i, Bundle bundle) {

     SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
     String minMagnitude = sharedPrefs.getString(
                 getString(R.string.settings_min_magnitude_key),
                 getString(R.string.settings_min_magnitude_default));
     Uri baseUri = Uri.parse(USGS_REQUEST_URL);
     Uri.Builder uriBuilder = baseUri.buildUpon();

     uriBuilder.appendQueryParameter("format", "geojson");
     uriBuilder.appendQueryParameter("limit", "10");
     uriBuilder.appendQueryParameter("minmag", minMagnitude);
     uriBuilder.appendQueryParameter("orderby", "time");

     return new EarthquakeLoader(this, uriBuilder.toString());
 }

We've inserted our minimum magnitude preference into the query URL! From the SettingsActivity in the UI, set the minimum magnitude to something small, and check out all the tiny earthquakes that just happened around the world.

For a summary of these changes, check out: https://github.com/udacity/ud843-QuakeReport/commit/2b291add9b079dee9b95bfccb7049071bab53d23